/**
 * 
 */
package wpmp.security.mgr.web;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import wpmp.extjs3.ExtjsUtils;
import wpmp.extjs3.data.Form;
import wpmp.extjs3.data.JsonStore;
import wpmp.security.client.utils.UserUtils;
import wpmp.security.mgr.Statics;
import wpmp.security.mgr.base.BaseAction;
import wpmp.security.mgr.base.DefaultBaseAction;
import wpmp.security.mgr.entity.Operation;
import wpmp.security.mgr.service.OperationService;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 3:08:18 PM Mar 18, 2013
 */
@Action("operation")
@Results({ @Result(name = BaseAction.LIST, location = "/WEB-INF/operation/list.jsp"),
		@Result(name = BaseAction.INPUT, location = "/WEB-INF/operation/input.jsp") })
public class OperationAction extends DefaultBaseAction<Operation> {

	private static final Logger LOG = LoggerFactory.getLogger(OperationAction.class);

	private static final long serialVersionUID = 1L;

	private OperationService service;

	@Autowired
	public void setService(OperationService service) {
		this.service = service;
	}

	public void listJSON() throws Exception {
		final List<Operation> records = service.list();
		for (Operation record : records) {
			record.setCreateUserName(UserUtils.getUserName(record.getCreateUser()));
			record.setUpdateUserName(UserUtils.getUserName(record.getUpdateUser()));
		}
		this.renderJson(new JsonStore<Operation>(records).toJSONString());
	}

	public void getJSON() throws Exception {
		final Operation result = service.get(entity.getId());

		if (LOG.isDebugEnabled()) {
			LOG.debug("{}", result);
		}

		if (result == null) {
			LOG.warn("can not found Operation by id[{}]", entity.getId());

			this.renderJson(ExtjsUtils.getDefaultErrorFormJSONString(Statics.DEFAULT_ERROR_MSG));
			return;
		}

		final String jsonString = Form.newInstance(result).toJSONString();

		if (LOG.isDebugEnabled()) {
			LOG.debug(jsonString);
		}

		this.renderJson(jsonString);
	}

	public void insertJSON() throws Exception {
		this.renderJson(service.insert(entity).toJSONString());
	}

	public void updateJSON() throws Exception {
		this.renderJson(service.update(entity).toJSONString());
	}

	public void deleteJSON() throws Exception {
		this.renderJson(service.delete(entity.getIds()).toJSONString());
	}

	public void sortJSON() throws Exception {
		this.renderJson(service.sort(entity.getIds()).toJSONString());
	}

	@Override
	public Operation getModel0() {
		if (entity == null) {
			entity = new Operation();
		}
		return entity;
	}
}
